package com.example.shiwu.util;

import android.content.SharedPreferences;

import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.google.firebase.crashlytics.buildtools.reloc.com.google.common.primitives.Bytes;

import org.json.JSONException;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class DataParseUtil {

    private final static String INDEX_ERR = "err";

    public static Map<String, Object> map;
    public static HashMap<String, Object> mapDouble;
    public static Object ob;
    private static Python py;
    private static PyObject pyobj, pyobjfft, pyobj1, pyobj2,pyobj3;
    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor editor;
    private ArrayList<String> tx_voltage = new ArrayList<String>();//发送电压
    private ArrayList<String> tx_current = new ArrayList<String>();//发射电流
    private ArrayList<String> rx_voltage = new ArrayList<String>();//接受电压

    public DataParseUtil() {
        super();
        initPy();
    }


    // 拼接字节组btA 和btB =btZ

    public static byte[] addTwoArray(byte[] btX, byte[] btY) {
        //定义目标数组  目标数组应该等于将要拼接的两个数组的总长度
        byte[] btZ = new byte[btX.length + btY.length];

        System.arraycopy(btX, 0, btZ, 0, btX.length);
        System.arraycopy(btY, 0, btZ, btX.length, btY.length);
        return btZ;
    }


    public static Double[] isEmpty(Object object) {
        int len = Array.getLength(object);
        Double[] obj = new Double[len];

        //数组判空
        if (object.getClass().isArray()) {
            for (int i = 0; i < len; i++) {
                System.out.println(Array.get(object, i));
                obj[i] = (Double) Array.get(object, i);
            }
        }
        return obj;
    }

    public static int isInt(Object object) {
        int len = Array.getLength(object);
        int obj = -1;

        //数组判空
        if (object.getClass().isArray()) {
            for (int i = 0; i < len; i++) {
                System.out.println(Array.get(object, i));
                obj = (int) Array.get(object, i);
            }
        }
        return obj;
    }

    public static int entiretyDecodeStructByteBack(byte[] val) {
        //initPy();
        return pyobj.callAttr("EntiretyDecodeStructByteBack", val).toInt();
    }

    public static int recv_unsigned_int(byte[] val) {
       // initPy();
        return pyobj.callAttr("_recv_unsigned_int", val).toInt();
    }


    public static String recv_float(byte[] val) {
        //initPy();
        return pyobj.callAttr("_recv_float", val).toString();
    }

    public static String recv_string(byte[] val) {
        // 用于拼接字符的StringBuilder
        StringBuilder result = new StringBuilder();

        // 遍历数组，将每个数字转换为对应的ASCII字符
        for (int num : val) {
            // 将整数强制转换为char（ASCII字符）
            char c = (char) num;
            result.append(c);
        }
        //initPy();
        return result.toString();
    }

    public static String jb2pb(byte[] val) {
       // initPy();
        return pyobjfft.callAttr("jb2pb", val).toString();
    }


    public static List<String> objToList(Object obj) {
        List<String> result = new ArrayList<String>();
        if (obj instanceof ArrayList<?>) {
            for (Object o : (List<?>) obj) {
                result.add(String.class.cast(o));
            }
        }
        return result;
    }

    public static List<Byte> objToByList(Object obj) {
        List<Byte> result = new ArrayList<Byte>();
        if (obj instanceof ArrayList<?>) {
            for (Object o : (List<?>) obj) {
                result.add(Byte.class.cast(o));
            }
        }
        return result;
    }

    public static byte[] listTobyte(List<Byte> list) {
        if (list == null || list.size() < 0)
            return null;
        byte[] bytes = new byte[list.size()];
        int i = 0;
        Iterator<Byte> iterator = list.iterator();
        while (iterator.hasNext()) {
            bytes[i] = iterator.next();
            i++;
        }
        return bytes;
    }
    public static byte[] listTobytes(List<Byte> list) {

        byte[] bytes= Bytes.toArray(list);

        return bytes;
    }


    /**
     * 拼接多帧数据组成不包含id,pulse_indx,pulse的数据 比如 AA55,。。。。。
     *
     * @return
     */


    public static String getDataForHeaderIndex(String str) {
        String strh, strh1, count;
        String strPulse_indx = "";
        String strPulse_count = "";
        int strHead = -1;
        if (str.length() > 0) {
            strh = str;

            if (strh.length() > 0) {
                //System.out.println("======================strh====================== "+strh);
                String[] strArray = str.substring(0, str.indexOf(";")).split(",");
                //System.out.println("======================strArray====================== "+strArray);
                if (strArray.length >= 3) {
                    strPulse_indx = strArray[1];
                    strPulse_count = strArray[2];
                    strHead = Integer.valueOf(strArray[0]);
                }

            }

        }
        return strHead + "," + strPulse_indx + "," + strPulse_count;
    }

    public static int bytesToInt(byte[] a) {
        int ans = 0;
        for (int i = 0; i < 4; i++) {
            ans <<= 8;//左移 8 位
            ans |= a[3 - i];//保存 byte 值到 ans 的最低 8 位上
            intPrint(ans);
        }
        return ans;
    }

    public static void intPrint(int a) {//将 int 按位从左到右打印
        int count = 0;
        for (int i = 31; i >= 0; i--) {
            System.out.print((a >> i) & 1);
            count++;
            if (count == 4) {//每四位为一组，用空格分开
                System.out.print(" ");
                count = 0;
            }
        }
        System.out.println();
    }

    //Object转Map
    public static Map<String, Object> getObjectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<String, Object>();
        Class<?> cla = obj.getClass();
        Field[] fields = cla.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String keyName = field.getName();
            Object value = field.get(obj);
            if (value == null)
                value = "";
            map.put(keyName, value);
        }
        return map;
    }

    private static void initPy() {
        py = Python.getInstance();
        pyobj = py.getModule("Struct_Data");
        pyobjfft = py.getModule("fft_ui");
        pyobj1 = py.getModule("ERT_UI_SECTION");
        //pyobj2 = py.getModule("ERT_UI_ARRAY_CVS1");
        pyobj2 = py.getModule("SECTION_ARRAY");
        pyobj3 = py.getModule("DataNormaliza");
    }

    public static String initPython(String val) throws JSONException, InterruptedException {
        initPy();
        String data = "";
//        if(!pyobj.callAttr("DecodeStruct", val).equals("null")){
//            data = String.valueOf(pyobj.callAttr("DecodeStruct", val).toJava(int.class));
//        }else{
        data = String.valueOf(pyobj.callAttr("DecodeStruct", val).toJava(Integer.class));
        //}

//        /System.out.println("-=-=-=-=-=-=-=-=-=-==- initPython_data ="+data);
        return data;
    }

    public static String DecodeUtfStruct(String val) throws JSONException, InterruptedException {
//        py = Python.getInstance();
//        pyobj = py.getModule("Struct_Data");
        //initPy();
        String data = String.valueOf(pyobj.callAttr("DecodeUtfStruct", val).toJava(String.class));
        //System.out.println("-=-=-=-=-=-=-=-=-=-==- DecodeUtfStruct_data ="+data);
        return data;
    }

    public static String DecodeTxVStruct(String val, Integer indx) throws JSONException, InterruptedException {
       // initPy();
        String data = "";
        if (!pyobj.callAttr("DecodeTxVStruct", val, indx).toString().equals("") && !pyobj.callAttr("DecodeTxVStruct", val, indx).toString().equals("null")) {
            data = String.valueOf(pyobj.callAttr("DecodeTxVStruct", val, indx).toJava(float.class));
        } else {//处理垃圾数据 发送 kConfirm 0
            if (pyobj.callAttr("DecodeTxVStruct", val, indx).toString().equals("null")) {
                data = "";
            } else {
                return INDEX_ERR;
            }

        }
        //System.out.println("-=-=-=-=-=-=-=-=-=-==- DecodeTxVStruct_data ="+data);
        return data;
    }

    public static String DecodeTxCStruct(String val, Integer indx) throws JSONException, InterruptedException {
        //initPy();
        String data = "";
        if (!pyobj.callAttr("DecodeTxCStruct", val, indx).toString().equals("") && !pyobj.callAttr("DecodeTxCStruct", val, indx).toString().equals("null")) {
            data = String.valueOf(pyobj.callAttr("DecodeTxCStruct", val, indx).toJava(float.class));
        } else {//处理垃圾数据 发送 kConfirm 0
            if (pyobj.callAttr("DecodeTxCStruct", val, indx).toString().equals("null")) {
                data = "";
            } else {
                return INDEX_ERR;
            }

        }
        //System.out.println("-=-=-=-=-=-=-=-=-=-==- DecodeTxCStruct_data ="+data);
        return data;
    }

    public static String DecodeRxVStruct(String val, Integer indx) throws JSONException, InterruptedException {
        //initPy();
        String data = "";
        if (!pyobj.callAttr("DecodeRxVStruct", val, indx).toString().equals("") && !pyobj.callAttr("DecodeRxVStruct", val, indx).toString().equals("null")) {
            data = String.valueOf(pyobj.callAttr("DecodeRxVStruct", val, indx).toJava(double.class));
        } else {//处理垃圾数据 发送 kConfirm 0
            if (pyobj.callAttr("DecodeRxVStruct", val, indx).toString().equals("null")) {
                data = "";
            } else {
                return INDEX_ERR;
            }

        }
        //System.out.println("-=-=-=-=-=-=-=-=-=-==- DecodeRxVStruct_data ="+data);
        return data;
    }

    public static int ERTuiSectionNs(String json) {
        //initPy();

        return pyobj1.callAttr("ERTuiSectionNs", json).toJava(int.class);
    }



    public static List<byte[]> SectionArray(String jb_tu, String json, String ns, int nss, int types,
                                      String obj1, String freq_Indx, Integer rx_voltage_data_len,
                                            int num_points, int numPoints1,int filter,int eleNum,int model,int CI,String ID) {
        //initPy();
        PyObject bytes = pyobj2.callAttr("SectionArray",jb_tu, json,ns,nss,types,
                obj1,freq_Indx, rx_voltage_data_len,num_points,numPoints1,filter,eleNum,model,CI,ID);
        List<PyObject>  lis = bytes.asList();
        List<byte[]> bylis = new ArrayList<byte[]>() ;
        if(lis.size()>0){
            for (int i = 0; i < lis.size(); i++) {
                bylis.add(lis.get(i).toJava(byte[].class));
            }
        }
        return bylis;
    }
    public static void ClosePlt() {
        //initPy();
        pyobj2.callAttr("ClosePlt");

    }

    public static void clearPkl(String id) {
        //initPy();
        pyobj2.callAttr("delete_pkl_file",id+".pkl");

    }


//    public static String[] dataNormaliza(BigDecimal[][] VIRO) {
//
//        //System.out.println(Arrays.deepToString(VIRO));
//        String bytes = pyobj3.callAttr("dataNormaliza", VIRO).toJava(String.class)
//                .replace("Decimal(","")
//                .replace(")","")
//                .replace("'","")
//                .replace("[","")
//                .replace("]","")
//                .replace(";", "\n");
//        //System.out.println("dataNormaliza ======= "+bytes);
//        String[] byArr = bytes.split(",");
//
//        return byArr;
//    }
    public static BigDecimal getKVal(Integer A,Integer B,Integer M,Integer N) {

        //System.out.println(Arrays.deepToString(VIRO));
        BigDecimal bytes = BigDecimal.valueOf(pyobj3.callAttr("getKVal", A,B,M,N).toJava(Double.class));
        //System.out.println("getKVal ======= "+bytes);
        return bytes;
    }

    public static double getFloat64(byte[] bytes) {
        return Double.longBitsToDouble(((bytes[0] & 0xFFL) << 56)
                | ((bytes[1] & 0xFFL) << 48)
                | ((bytes[2] & 0xFFL) << 40)
                | ((bytes[3] & 0xFFL) << 32)
                | ((bytes[4] & 0xFFL) << 24)
                | ((bytes[5] & 0xFFL) << 16)
                | ((bytes[6] & 0xFFL) << 8)
                | ((bytes[7] & 0xFFL) << 0));
    }

    /**
     * 将byte类型的arr转换成float
     *
     * @return
     */
    public static List<Float> byteArrayToFloatList(byte[] bytes) {
        List<Float> d = new ArrayList<>(bytes.length / 8);
        byte[] doubleBuffer = new byte[4];
        for (int j = 0; j < bytes.length; j += 4) {
            System.arraycopy(bytes, j, doubleBuffer, 0, doubleBuffer.length);
            d.add(bytes2Float(doubleBuffer));
        }
        return d;
    }

    /**
     * 将byte数组数据转换成float
     *
     * @param arr
     * @return
     */
    public static float bytes2Float(byte[] arr) {
        int accum = 0;
        accum = accum | (arr[0] & 0xff) << 0;
        accum = accum | (arr[1] & 0xff) << 8;
        accum = accum | (arr[2] & 0xff) << 16;
        accum = accum | (arr[3] & 0xff) << 24;
        return Float.intBitsToFloat(accum);
    }

    // 从byte数组的index处的连续4个字节获得一个float
    public static float getFloat(byte[] arr, int index) {
        return Float.intBitsToFloat(getInt(arr, index));
    }

    // 从byte数组的index处的连续4个字节获得一个int
    public static int getInt(byte[] arr, int index) {
        return (0xff000000 & (arr[index + 0] << 24)) |
                (0x00ff0000 & (arr[index + 1] << 16)) |
                (0x0000ff00 & (arr[index + 2] << 8)) |
                (0x000000ff & arr[index + 3]);
    }

    public static void setPageLens(Integer packetLens) {
        //initPy();
        pyobj.callAttr("SetPageLens", packetLens);
    }


    public static String recv_short(byte[] val) {
        return pyobj.callAttr("recv_short", val).toString();
    }
}
